import { EMessageType, IMessage, IMessageData } from "../utils";

import {
  sendKeywordRequest,
  sendRemoveRequest,
  sendSearchRequest,
} from "./sendRequest";

/** 消息的处理逻辑 */
const actions = {
  [EMessageType.Keyword]: (
    { params }: IMessage<Record<EMessageType, IMessageData[EMessageType]>>,
    _: chrome.runtime.MessageSender,
    sendResponse: (data: any) => void
  ): boolean => {
    const p = params as unknown as IMessageData[EMessageType.Keyword];
    sendKeywordRequest(p.keyword)
      .then((result) => {
        sendResponse(result);
      })
      .catch(() => {
        sendResponse(undefined);
      });
    return true;
  },
  [EMessageType.Search]: (
    { params }: IMessage<Record<EMessageType, IMessageData[EMessageType]>>,
    _: chrome.runtime.MessageSender,
    sendResponse: (data: any) => void
  ): boolean => {
    const p = params as unknown as IMessageData[EMessageType.Search];
    sendResponse(sendSearchRequest(p.keyword));
    return false;
  },
  [EMessageType.RemoveHistory]: (
    { params }: IMessage<Record<EMessageType, IMessageData[EMessageType]>>,
    _: chrome.runtime.MessageSender,
    sendResponse: (data: any) => void
  ): boolean => {
    const p = params as unknown as IMessageData[EMessageType.RemoveHistory];
    sendRemoveRequest(p.keyword)
      .then((result) => {
        sendResponse(result);
      })
      .catch(() => {
        sendResponse(undefined);
      });
    return true;
  }
};

/** 监听消息 */
chrome.runtime.onMessage.addListener(function (
  message: IMessage<Record<EMessageType, IMessageData[EMessageType]>>,
  _: chrome.runtime.MessageSender,
  sendResponse: (data: any) => void
) {
  return actions[message.id]?.(message, _, sendResponse);
});
